//
//  NITextFieldView.m
//  AIWAYS
//
//  Created by Marx on 2018/6/11.
//  Copyright © 2018年 wlq. All rights reserved.
//


#define NIColorLineColor [UIColor colorWithRed:218.0/255.0 green:224.0/255.0 blue:227.0/255.0 alpha:1.0]
#define NIColorLineLightColor [UIColor colorWithRed:244.0/255.0 green:119.0/255.0 blue:119.0/255.0 alpha:1.0]

#define NIColorTextFieldPlaceholderColor [UIColor colorWithRed:189.0/255.0 green:206.0/255.0 blue:219.0/255.0 alpha:1.0]
#define NIColorTextFieldTextColor [UIColor colorWithRed:72.0/255.0 green:81.0/255.0 blue:87.0/255.0 alpha:1.0]


#import "NITextFieldView.h"
#import "NITextField.h"
#import "UITextField+NavInfo.h"
#import "NSString+Navinfo.h"
#import "NIBaseViewController.h"
#import "NSString+Navinfo.h"

@interface NITextFieldView()<UITextFieldDelegate>
{
    __weak IBOutlet UIView *contentView;
    __weak IBOutlet UIImageView *iconImageView;
    __weak IBOutlet NITextField *textField;
    __weak IBOutlet UIImageView *lineImageView;
    __weak IBOutlet UIButton *eyeButton;
    __weak IBOutlet NSLayoutConstraint *eyeButtonLayoutConstraintWidth;
    
    __weak IBOutlet NSLayoutConstraint *eyeButtonLayoutConstraintTrailing;
    __weak IBOutlet NSLayoutConstraint *iconLayoutConstraintWidthLY;
    
    __weak IBOutlet UILabel *titleLabel;
    BOOL pwdIsVisible;
    NSInteger maxTextLength;
    NSInteger maxTextCharLength;
    BOOL canInputChinese;
    
    BOOL isPwd;
    __weak IBOutlet NSLayoutConstraint *titleAndContentIntervalWidthLY;
    
}

@end
@implementation NITextFieldView

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self awakeFromNib];
    }
    return self;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self awakeFromNib];
    }
    return self;
}


-(void)awakeFromNib
{
    [super awakeFromNib];
    [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self.class) owner:self options:nil];
    
    [self addSubview:contentView];
    
    contentView.translatesAutoresizingMaskIntoConstraints = NO;
    [self addConstraint:[NSLayoutConstraint constraintWithItem:contentView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:contentView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0]];
    
    [self addConstraint:[NSLayoutConstraint constraintWithItem:contentView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0.0]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:contentView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0.0]];
    
    
    [textField setTextColor:NIColorTextFieldTextColor];
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidBeginEditing:) name:UITextFieldTextDidBeginEditingNotification object:textField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidEndEditing:) name:UITextFieldTextDidEndEditingNotification object:textField];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChange:) name:UITextFieldTextDidChangeNotification object:textField];
    
    
    eyeButton.hidden = YES;
    eyeButtonLayoutConstraintWidth.constant = 0;
    [eyeButton setImage:[UIImage imageNamed:@"login_eye_off"] forState:UIControlStateNormal];
    pwdIsVisible = NO;
    
    textField.delegate = self;
    textField.returnKeyType = UIReturnKeyDone;
    maxTextLength = NSIntegerMax;
    
    iconLayoutConstraintWidthLY.constant = 0;
    
    canInputChinese = YES;
    titleLabel.text = @"";
}


-(void)reloadEyeButtonAndTextField
{
    if (pwdIsVisible == NO) {
        
        [eyeButton setImage:[UIImage imageNamed:@"login_eye_off"] forState:UIControlStateNormal];
    }
    else
    {
        
        [eyeButton setImage:[UIImage imageNamed:@"login_eye_on"] forState:UIControlStateNormal];
        
    }
    BOOL isFirstResponder = [textField isFirstResponder];
    //避免明文/密文切换后光标位置偏移
    textField.enabled = NO;    // the first one;
    textField.secureTextEntry = !pwdIsVisible;
    textField.enabled = YES;  // the second one;
    if (isFirstResponder) {
        [textField becomeFirstResponder]; // the third one
    }
    
}

#pragma mark - 外部方法
-(void)setSecureTextEntry:(BOOL)isSecure
{
    isPwd = isSecure;
    [textField setIsSecure:isSecure];
    if (isSecure) {
        if (textField.text && ![textField.text isEqualToString:@""]) {
            eyeButton.hidden = NO;
        }
        else
        {
            eyeButton.hidden = YES;
        }
        eyeButtonLayoutConstraintWidth.constant = 32;
        [self reloadEyeButtonAndTextField];
    }
    else
    {
        eyeButton.hidden = YES;
        eyeButtonLayoutConstraintWidth.constant = 0;
        textField.secureTextEntry = NO;
    }
    
}

-(void)setTextKeyboardType:(UIKeyboardType)type
{
    if (type == UIKeyboardTypeNumberPad ||type == UIKeyboardTypeASCIICapable) {
        canInputChinese = NO;
    }
    textField.keyboardType = type;
}

-(void)setText:(NSString *)text
{
    if (text) {
        if (self.checkNickname) {
            textField.text = [text filterCharactorForNickname];
        }
        else
        {
            
            textField.text = text;
            
        }
    }
    else
    {
        textField.text = @"";
    }
    if (isPwd && text && ![text isEqualToString:@""]) {
        eyeButton.hidden = NO;
    }
    else
    {
        eyeButton.hidden = YES;
    }
}

-(void)setPlaceholder:(NSString *)placeholder
{
    if (placeholder && ![placeholder isEqualToString:@""]) {
        
        textField.placeholder = placeholder;
        textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:textField.placeholder attributes:@{NSForegroundColorAttributeName: NIColorTextFieldPlaceholderColor}];
    }
    else
    {
        
        textField.placeholder = @"";
    }
}

-(NSString *)getText
{
    return textField.text;
}

-(void)setTextFieldTrailing:(float)trailing
{
//    eyeButtonLayoutConstraintTrailing.constant = trailing;
}

-(void)textFieldResignFirstResponder
{
    [textField resignFirstResponder];
}

-(void)textFieldBecomeFirstResponder
{
    [textField becomeFirstResponder];
}

-(void)setMaxLength:(NSInteger)maxLength
{
    maxTextLength = maxLength;
    [textField setLimitMaxTextLength:maxLength];
}
-(void)setMaxCharLength:(NSInteger)maxCharLength
{
    maxTextCharLength = maxCharLength;
}

-(void)setIconImageName:(NSString *)imageName
{
    if (imageName && ![imageName isEqualToString:@""]) {
        
        [iconImageView setImage:[UIImage imageNamed:imageName]];
        iconLayoutConstraintWidthLY.constant = 20;
    }
    else
    {
        iconLayoutConstraintWidthLY.constant = 0;
    }
}

-(void)setLineHighlight:(BOOL)highlight
{
    if (highlight) {
        [lineImageView setBackgroundColor:NIColorLineLightColor];
    }
    else
    {
        [lineImageView setBackgroundColor:NIColorLineColor];
    }
}

-(void)setTitle:(NSString *)title
{
    titleLabel.text = title;
}



#pragma mark - action

- (IBAction)onClickEyeButton:(id)sender {
    
    pwdIsVisible = !pwdIsVisible;
    [self reloadEyeButtonAndTextField];
}

#pragma mark - notification action
// 获得焦点
- (void)textFieldDidBeginEditing:(NSNotification *)sender{
//    [lineImageView setBackgroundColor:NIColorLineLightColor];
}

// 失去焦点
- (void)textFieldDidEndEditing:(NSNotification *)sender{
//    [lineImageView setBackgroundColor:NIColorLineColor];
    if (!canInputChinese) {
        textField.text = [textField.text filterCharactorForPassword];
    }
    if (self.checkNickname) {
        textField.text = [textField.text filterCharactorForNickname];
    }
    if (maxTextCharLength > 0) {
        if ([textField.text validStrlength] > maxTextCharLength) {
            for (NSInteger i = textField.text.length - 1; i >= 0; i--) {
                NSString *str = [textField.text substringToIndex:i];
                if ([str validStrlength] <= maxTextCharLength) {
                    textField.text = str;
                    break;
                }
            }
        }
    }
}


- (void)textFieldDidChange:(NSNotification *)sender{
    UITextRange *selectedRange = textField.markedTextRange;
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    
    if (!position) { // 没有高亮选择的字
        //过滤除数字字母外符号
        if (!canInputChinese) {
            textField.text = [textField.text filterCharactorForPassword];
        }
        if (self.checkNickname) {
            textField.text = [textField.text filterCharactorForNickname];
        }
        if (maxTextCharLength > 0) {
            if ([textField.text validStrlength] > maxTextCharLength) {
                for (NSInteger i = textField.text.length - 1; i >= 0; i--) {
                    NSString *str = [textField.text substringToIndex:i];
                    if ([str validStrlength] <= maxTextCharLength) {
                        textField.text = str;
                        break;
                    }
                }
            }
        }
        
    }else { //有高亮文字
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(textFieldDidChange:)]) {
        [self.delegate textFieldDidChange:textField.text];
    }
    
}


-(void)setTitleAndContentIntervalWidth:(float)interval
{
    titleAndContentIntervalWidthLY.constant = -interval;
}



#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //明文切换密文后避免被清空
    NSString *toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (isPwd && toBeString && ![toBeString isEqualToString:@""]) {
        eyeButton.hidden = NO;
    }
    else
    {
        eyeButton.hidden = YES;
    }
    
    if (textField.isSecureTextEntry) {
        if (toBeString.length > maxTextLength) {
            textField.text = [toBeString substringToIndex:maxTextLength];
            NSLog(@"已输入最大位数");
            [textField resignFirstResponder];
            UINavigationController *nv= (UINavigationController *)[UIApplication sharedApplication].delegate.window.rootViewController;
            NIBaseViewController *vc = (NIBaseViewController *)nv.viewControllers[[nv.viewControllers count]-1];
//            [vc showToast:[NSString stringWithFormat:@"输入内容不能大于%ld位",(long)maxTextLength]];
        }
        else
        {
            textField.text = toBeString;
        }
        if (self.delegate && [self.delegate respondsToSelector:@selector(textFieldDidChange:)]) {
            [self.delegate textFieldDidChange:textField.text];
        }
        return NO;
    }
    return YES;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    BOOL flag = NO;
    
    [textField resignFirstResponder];
    return flag;
}




/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
